﻿#include "can.h"

Can::Can() : QObject() {

	m_currentSettings.pluginName = m_ui->pluginListBox->currentText();
	m_currentSettings.deviceInterfaceName = m_ui->interfaceListBox->currentText();
	m_currentSettings.useConfigurationEnabled = m_ui->useConfigurationBox->isChecked();

	if (m_currentSettings.useConfigurationEnabled) {
		m_currentSettings.configurations.clear();
		// process LoopBack
		if (m_ui->loopbackBox->currentIndex() != 0) {
			ConfigurationItem item;
			item.first = QCanBusDevice::LoopbackKey;
			item.second = m_ui->loopbackBox->currentData();
			m_currentSettings.configurations.append(item);
		}

		// process ReceiveOwnKey
		if (m_ui->receiveOwnBox->currentIndex() != 0) {
			ConfigurationItem item;
			item.first = QCanBusDevice::ReceiveOwnKey;
			item.second = m_ui->receiveOwnBox->currentData();
			m_currentSettings.configurations.append(item);
		}

		// process error filter
		if (!m_ui->errorFilterEdit->text().isEmpty()) {
			QString value = m_ui->errorFilterEdit->text();
			bool ok = false;
			int dec = value.toInt(&ok);
			if (ok) {
				ConfigurationItem item;
				item.first = QCanBusDevice::ErrorFilterKey;
				item.second = QVariant::fromValue(QCanBusFrame::FrameErrors(dec));
				m_currentSettings.configurations.append(item);
			}
		}

		// process raw filter list
		if (!m_ui->rawFilterEdit->text().isEmpty()) {
			//TODO current ui not sfficient to reflect this param
		}

		// process bitrate
		const int bitrate = m_ui->bitrateBox->bitRate();
		if (bitrate > 0) {
			const ConfigurationItem item(QCanBusDevice::BitRateKey, QVariant(bitrate));
			m_currentSettings.configurations.append(item);
		}

		// process CAN FD setting
		ConfigurationItem fdItem;
		fdItem.first = QCanBusDevice::CanFdKey;
		fdItem.second = m_ui->canFdBox->currentData();
		m_currentSettings.configurations.append(fdItem);

		// process data bitrate
		const int dataBitrate = m_ui->dataBitrateBox->bitRate();
		if (dataBitrate > 0) {
			const ConfigurationItem item(QCanBusDevice::DataBitRateKey, QVariant(dataBitrate));
			m_currentSettings.configurations.append(item);
		}
	}
}

void Can::initActionsConnections()
{
	//	m_ui->actionDisconnect->setEnabled(false);
	//	m_ui->sendFrameBox->setEnabled(false);

	//	connect(m_ui->sendFrameBox, &SendFrameBox::sendFrame, this, &MainWindow::sendFrame);
	//	connect(m_ui->actionConnect, &QAction::triggered, [this]() {
	//		m_canDevice.release()->deleteLater();
	//		m_connectDialog->show();
	//		});
	//	connect(m_connectDialog, &QDialog::accepted, this, &MainWindow::connectDevice);
	//	connect(m_ui->actionDisconnect, &QAction::triggered, this, &MainWindow::disconnectDevice);
	//	connect(m_ui->actionResetController, &QAction::triggered, this, [this]() {
	//		m_canDevice->resetController();
	//		});
	//	connect(m_ui->actionQuit, &QAction::triggered, this, &QWidget::close);
	//	connect(m_ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
	//	connect(m_ui->actionClearLog, &QAction::triggered, m_ui->receivedMessagesEdit, &QTextEdit::clear);
	//	connect(m_ui->actionPluginDocumentation, &QAction::triggered, this, []() {
	//		QDesktopServices::openUrl(QUrl("http://doc.qt.io/qt-5/qtcanbus-backends.html#can-bus-plugins"));
	//		});
}

void Can::processErrors(QCanBusDevice::CanBusError error) const
{
	switch (error) {
	case QCanBusDevice::ReadError:
	case QCanBusDevice::WriteError:
	case QCanBusDevice::ConnectionError:
	case QCanBusDevice::ConfigurationError:
	case QCanBusDevice::UnknownError:
		//	m_status->setText(m_canDevice->errorString());
		break;
	default:
		break;
	}
}

void Can::connectDevice()
{
	const  Settings p = m_connectDialog->settings();

	QString errorString;
	m_canDevice.reset(QCanBus::instance()->createDevice(p.pluginName, p.deviceInterfaceName,
		&errorString));
	if (!m_canDevice) {
		m_status->setText(tr("Error creating device '%1', reason: '%2'")
			.arg(p.pluginName).arg(errorString));
		return;
	}

	m_numberFramesWritten = 0;

	connect(m_canDevice.get(), &QCanBusDevice::errorOccurred,
		this, &MainWindow::processErrors);
	connect(m_canDevice.get(), &QCanBusDevice::framesReceived,
		this, &MainWindow::processReceivedFrames);
	connect(m_canDevice.get(), &QCanBusDevice::framesWritten,
		this, &MainWindow::processFramesWritten);

	if (p.useConfigurationEnabled) {
		for (const ConnectDialog::ConfigurationItem& item : p.configurations)
			m_canDevice->setConfigurationParameter(item.first, item.second);
	}

	if (!m_canDevice->connectDevice()) {
		m_status->setText(tr("Connection error: %1").arg(m_canDevice->errorString()));

		m_canDevice.reset();
	}
	else {
		m_ui->actionConnect->setEnabled(false);
		m_ui->actionDisconnect->setEnabled(true);

		m_ui->sendFrameBox->setEnabled(true);

		const QVariant bitRate = m_canDevice->configurationParameter(QCanBusDevice::BitRateKey);
		if (bitRate.isValid()) {
			const bool isCanFd =
				m_canDevice->configurationParameter(QCanBusDevice::CanFdKey).toBool();
			const QVariant dataBitRate =
				m_canDevice->configurationParameter(QCanBusDevice::DataBitRateKey);
			if (isCanFd && dataBitRate.isValid()) {
				m_status->setText(tr("Plugin: %1, connected to %2 at %3 / %4 kBit/s")
					.arg(p.pluginName).arg(p.deviceInterfaceName)
					.arg(bitRate.toInt() / 1000).arg(dataBitRate.toInt() / 1000));
			}
			else {
				m_status->setText(tr("Plugin: %1, connected to %2 at %3 kBit/s")
					.arg(p.pluginName).arg(p.deviceInterfaceName)
					.arg(bitRate.toInt() / 1000));
			}
		}
		else {
			m_status->setText(tr("Plugin: %1, connected to %2")
				.arg(p.pluginName).arg(p.deviceInterfaceName));
		}

		if (m_canDevice->hasBusStatus())
			m_busStatusTimer->start(2000);
		else
			m_ui->busStatus->setText(tr("No CAN bus status available."));
	}
}

void Can::busStatus()
{
	if (!m_canDevice || !m_canDevice->hasBusStatus()) {
		m_ui->busStatus->setText(tr("No CAN bus status available."));
		m_busStatusTimer->stop();
		return;
	}

	switch (m_canDevice->busStatus()) {
	case QCanBusDevice::CanBusStatus::Good:
		m_ui->busStatus->setText("CAN bus status: Good.");
		break;
	case QCanBusDevice::CanBusStatus::Warning:
		m_ui->busStatus->setText("CAN bus status: Warning.");
		break;
	case QCanBusDevice::CanBusStatus::Error:
		m_ui->busStatus->setText("CAN bus status: Error.");
		break;
	case QCanBusDevice::CanBusStatus::BusOff:
		m_ui->busStatus->setText("CAN bus status: Bus Off.");
		break;
	default:
		m_ui->busStatus->setText("CAN bus status: Unknown.");
		break;
	}
}

void Can::disconnectDevice()
{
	if (!m_canDevice)
		return;

	m_busStatusTimer->stop();

	m_canDevice->disconnectDevice();

	m_ui->actionConnect->setEnabled(true);
	m_ui->actionDisconnect->setEnabled(false);

	m_ui->sendFrameBox->setEnabled(false);

	m_status->setText(tr("Disconnected"));
}

void Can::processFramesWritten(qint64 count)
{
	m_numberFramesWritten += count;
	m_written->setText(tr("%1 frames written").arg(m_numberFramesWritten));
}

void Can::closeEvent(QCloseEvent* event)
{
	m_connectDialog->close();
	event->accept();
}

static QString frameFlags(const QCanBusFrame& frame)
{
	QString result = QLatin1String(" --- ");

	if (frame.hasBitrateSwitch())
		result[1] = QLatin1Char('B');
	if (frame.hasErrorStateIndicator())
		result[2] = QLatin1Char('E');
	if (frame.hasLocalEcho())
		result[3] = QLatin1Char('L');

	return result;
}

void Can::processReceivedFrames()
{
	if (!m_canDevice)
		return;

	while (m_canDevice->framesAvailable()) {
		const QCanBusFrame frame = m_canDevice->readFrame();

		QString view;
		if (frame.frameType() == QCanBusFrame::ErrorFrame)
			view = m_canDevice->interpretErrorFrame(frame);
		else
			view = frame.toString();

		const QString time = QString::fromLatin1("%1.%2  ")
			.arg(frame.timeStamp().seconds(), 10, 10, QLatin1Char(' '))
			.arg(frame.timeStamp().microSeconds() / 100, 4, 10, QLatin1Char('0'));

		const QString flags = frameFlags(frame);

		m_ui->receivedMessagesEdit->append(time + flags + view);
	}
}

void Can::sendFrame(const QCanBusFrame& frame) const
{
	if (!m_canDevice)
		return;

	m_canDevice->writeFrame(frame);
}
